﻿using BlogDemo.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BlogDemo.Data
{
    public class RepositoryContext : DisposableBase, IRepositoryContext
    {

        private readonly object _sync = new object();
        public IDbConnection Connection { set; get; }
        public IDbTransaction Transaction { private set; get; }

        public bool IsCommitted { set; get; }


        public RepositoryContext()
        {
            IsCommitted = true;
        }

        #region IUnitOfWork Support
        public virtual void BeginTransaction()
        {
            this.Transaction = this.Connection.BeginTransaction();
            this.IsCommitted = false;
        }


        public virtual void Rollback()
        {
            if (IsCommitted) return;
            lock (_sync)
            {
                this.Transaction.Rollback();
                this.IsCommitted = true;
            }
        }
        public virtual int Commit()
        {
            if (IsCommitted) return -1;
            lock (_sync)
            {
                this.Transaction.Commit();
                this.IsCommitted = true;
                return 1;
            }
        }
        public async virtual Task<int> CommitAsync()
        {
            if (IsCommitted) return await Task.Run(() => -1);

            return await Task.Run(() =>
            {
                lock (_sync)
                {
                    this.Transaction.Commit();
                    this.IsCommitted = true;
                }
                return 1;
            });
        }
        #endregion

        #region IDisposable Support
        protected override void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }
            if (this.Connection.State != ConnectionState.Open) return;
            Commit();
            this.Connection.Close();
            this.Connection.Dispose();
        }
        #endregion

        #region IRepositoryContext Support
        public virtual void RegisterNew<TEntity>(TEntity entity) where TEntity : class
        {
            throw new NotImplementedException();
        }

        public virtual void RegisterModified<TEntity>(TEntity entity) where TEntity : class
        {
            throw new NotImplementedException();
        }

        public virtual void RegisterDeleted<TEntity>(TEntity entity) where TEntity : class
        {
            throw new NotImplementedException();
        }
        #endregion

    }
}